package com.example.rabbitmq.service;

import com.example.rabbitmq.config.DeadLetterConfig;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class DelayMessageService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    // 发送延迟消息
    public void sendDelayMessage(String message, long delayMillis) {
        // 创建消息属性
        MessageProperties properties = new MessageProperties();
        // 设置消息过期时间
        properties.setExpiration(String.valueOf(delayMillis));

        // 创建消息
        Message msg = new Message(message.getBytes(), properties);

        System.out.println("发送延迟消息: " + message + "，延迟时间: " + delayMillis + "ms");

        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());

        // 发送到普通队列
        rabbitTemplate.send(DeadLetterConfig.NORMAL_EXCHANGE, DeadLetterConfig.NORMAL_ROUTING_KEY, msg, correlationData);
    }
}
